<template>
  <div>
    <el-collapse-transition>
      <card-search v-if="searchCardShow">
        <el-form ref="form" :model="form" label-width="80px" :inline="true">
          <el-form-item label="操作人员">
            <el-input v-model="form.operName" style="width: 250px" clearable />
          </el-form-item>
          <el-form-item label="操作类型">
            <el-select
              v-model="form.businessType"
              placeholder="请选择"
              style="width: 250px"
              clearable
            >
              <el-option
                v-for="item in getDictLabel('sys_oper_type')"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="操作状态">
            <el-select
              v-model="form.status"
              placeholder="请选择"
              style="width: 250px"
              clearable
            >
              <el-option
                v-for="item in getDictLabel('sys_common_status')"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="操作时间">
            <el-date-picker
              v-model="createTime"
              style="width: 250px"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              @change="handleSelectTime"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              class="btn-search"
              round
              icon="el-icon-search"
              size="medium"
              @click="initTable"
              >搜索</el-button
            >
            <el-button
              class="btn-search"
              round
              icon="el-icon-refresh"
              size="medium"
              @click="resetTable"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </card-search>
    </el-collapse-transition>

    <card-table style="height: calc(100vh - 100px)">
      <div class="card-table-header">
        <div class="card-table-header-btns">
          <el-button
            v-if="isSuperAdmin || hasPermission('monitor:operlog:remove')"
            class="btn-search"
            size="small"
            icon="el-icon-delete"
            :disabled="btnDisabled"
            @click="handleClick(null, 'delete')"
            >删除</el-button
          >
          <el-button
            v-if="isSuperAdmin || hasPermission('monitor:operlog:remove')"
            class="btn-search"
            size="small"
            icon="el-icon-circle-close"
            @click="handleClick(null, 'clear')"
            >清空</el-button
          >
          <el-button
            class="btn-search"
            size="small"
            icon="el-icon-upload2"
            @click="handleClick(null, 'export')"
            v-if="isSuperAdmin || hasPermission('monitor:operlog:export')"
            >导出</el-button
          >
          <el-input
            v-if="isSuperAdmin || hasPermission('monitor:operlog:list')"
            v-model="form.title"
            placeholder="请输入系统模块名称"
            style="width: 450px; margin-left: 10px"
            clearable
            size="small"
            @change="initTable"
          >
            <el-button slot="append" icon="el-icon-search" @click="initTable"></el-button>
          </el-input>
        </div>
        <div class="card-table-header-actions">
          <table-action
            :table-header="tableHeader"
            @check-change="handleCheckChange"
            @search-click="handleSearchClick"
            @init-click="handleInitClick"
          />
        </div>
      </div>
      <el-table
        :key="tableKey"
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        :header-cell-style="{ background: '#eff3f8', color: '#333' }"
        border
        stripe
        :default-sort="{ prop: 'date', order: 'descending' }"
        :max-height="tableHeight"
        @selection-change="handleSelectionChange"
        size="small"
        highlight-selection-row
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          v-for="item in tableHeader"
          v-if="item.visible"
          :key="item.prop"
          :label="item.title"
          :min-width="item.width"
          :prop="item.prop"
          sortable
          :align="item.align"
        >
          <template #default="scope">
            <span v-if="item.prop === 'businessType'" class="link-type">{{
              getDictText("sys_oper_type", scope.row[item.prop])
            }}</span>
            <span v-else-if="item.prop === 'status'" class="link-type">
              {{ getDictText("sys_common_status", scope.row[item.prop]) }}</span
            >
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          nin-width="100"
          align="center"
          v-if="isSuperAdmin || hasPermission('monitor:operlog:detail')"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-document"
              @click="handleClick(scope.row, 'view')"
              >详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <XyPagination
        :total="total"
        :pageSizeNum="pageSize"
        :pageNum="currentPage"
        @pagination="handlerPagination"
      ></XyPagination>
    </card-table>
    <dialog-action-log
      v-model="dialogVisible"
      :field="field"
      :rowData="rowData"
      :dictCache="dictCache"
      @close="
        () => {
          dialogVisible = false;
        }
      "
    />
  </div>
</template>
<script>
import CardSearch from "@/components/CardSearch";
import CardTable from "@/components/CardTable";
import TableAction from "@/components/TableAction";
import XyPagination from "@/components/XyPagination";
import { hasPermission, isSuperAdmin } from "@/utils/hasBtnPermission";
import DialogActionLog from "./component/DialogActionLog.vue";
import {
  operateLogList,
  queryDictData,
  operateLogExport,
  operateLogRemove,
  cleanOperateLog,
} from "@/api/systemmanagement";
export default {
  name: "ActionLogList",
  components: {
    CardSearch,
    CardTable,
    TableAction,
    DialogActionLog,
    XyPagination,
  },
  data() {
    return {
      tableKey: 0, // 用于强制刷新表格
      searchCardShow: false,
      dialogVisible: false,
      tableHeight: 550,
      field: "",
      form: {
        status: "",
        title: "",
        beginTime: "",
        finishTime: "",
        operName: "",
        businessType: "",
      },
      createTime: [],
      options: [
        {
          value: "0",
          label: "所有",
        },
        {
          value: "1",
          label: "正常",
        },
        {
          value: "2",
          label: "停用",
        },
      ],
      value: "0",
      tableHeader: [
        {
          title: "日志编号",
          prop: "operId",
          width: "100",
          align: "center",
          visible: true,
        },
        {
          title: "系统模块",
          prop: "title",
          width: "150",
          align: "center",
          visible: true,
        },
        {
          title: "操作类型",
          prop: "businessType",
          width: "120",
          align: "center",
          visible: true,
        },
        {
          title: "操作人员",
          prop: "operName",
          width: "120",
          align: "center",
          visible: true,
        },
        {
          title: "部门名称",
          prop: "deptName",
          width: "120",
          align: "center",
          visible: true,
        },
        {
          title: "主机",
          prop: "operIp",
          width: "120",
          align: "center",
          visible: true,
        },
        {
          title: "操作地点",
          prop: "operLocation",
          width: "120",
          align: "center",
          visible: true,
        },
        {
          title: "操作状态",
          prop: "status",
          width: "120",
          align: "center",
          visible: true,
        },
        {
          title: "操作时间",
          prop: "operTime",
          width: "120",
          align: "center",
          visible: true,
        },
      ],
      tableData: [],
      multipleSelection: [],
      btnDisabled: true,
      currentPage: 1,
      pageSize: 20,
      total: 0,
      dictCache: {}, // 字典缓存
      rowData: {},
    };
  },
  computed: {
    isSuperAdmin() {
      return isSuperAdmin();
    },
  },
  async mounted() {
    this.calculateTableHeight();
    // 预加载操作类型和状态字典
    await Promise.all([
      this.loadDictData("sys_oper_type"),
      this.loadDictData("sys_common_status"),
    ]);
    this.initTable();
  },
  methods: {
    initTable() {
      let data = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        title: this.form.title,
        operName: this.form.operName,
        businessType: this.form.businessType,
        status: this.form.status,
        "params[beginTime]": this.form.beginTime,
        "params[endTime]": this.form.finishTime,
      };
      operateLogList(data).then((res) => {
        // 预处理数据，获取字典值
        this.tableData = res.rows;
        this.total = res.total;
      });
    },

    getDictLabel(val) {
      // 如果已有缓存，直接返回
      if (this.dictCache[val]) {
        return this.dictCache[val];
      }
      // 否则请求数据并缓存
      queryDictData({ dictType: val })
        .then((res) => {
          this.$set(this.dictCache, val, res.data);
          // 强制更新相关组件
          this.$forceUpdate();
        })
        .catch((error) => {
          console.error("获取字典数据失败:", error);
          this.$set(this.dictCache, val, []);
        });

      // 先返回空数组
      return [];
    },

    getDictText(dictType, value) {
      // 检查是否有缓存数据
      if (this.dictCache[dictType] && Array.isArray(this.dictCache[dictType])) {
        // 在缓存的字典数据中查找匹配项
        const matchedItem = this.dictCache[dictType].find((item) => {
          // 支持多种匹配方式
          return (
            item.dictValue == value || item.dictLabel == value || item.dictCode == value
          );
        });

        // 如果找到匹配项，返回标签文本
        if (matchedItem) {
          return matchedItem.dictLabel || matchedItem.dictValue;
        }
      }

      // 如果没有找到匹配项或没有缓存，返回原始值
      return value;
    },
    async loadDictData(dictType) {
      // 如果已经有缓存，直接返回
      if (this.dictCache[dictType]) {
        return this.dictCache[dictType];
      }

      try {
        // 调用API获取字典数据
        const response = await queryDictData({ dictType: dictType });
        // 缓存数据
        this.$set(this.dictCache, dictType, response.data || []);
        return response.data || [];
      } catch (error) {
        console.error(`加载字典数据失败: ${dictType}`, error);
        this.$set(this.dictCache, dictType, []);
        return [];
      }
    },

    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      if (this.multipleSelection.length > 0) {
        this.btnDisabled = false;
      } else {
        this.btnDisabled = true;
      }
      console.log(this.multipleSelection);
    },
    handleClick(row, field) {
      switch (field) {
        case "view":
          this.field = "操作日志详情";
          this.dialogVisible = true;
          this.rowData = row;
          break;
        case "delete":
          this.$confirm(
            `确认删除选中的${this.multipleSelection.length}个日志吗?`,
            "系统提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          ).then(() => {
            let data = {
              ids: this.multipleSelection.map((item) => item.operId),
            };
            operateLogRemove(data).then((res) => {
              if (res == 0) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.initTable();
              }
            });
          });
          break;
        case "clear":
          this.$confirm(`确认清空所有日志吗?`, "系统提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            cleanOperateLog().then((res) => {
              if (res == 0) {
                this.$message({
                  type: "success",
                  message: res.msg,
                });
                this.initTable();
              }
            });
          });
          break;
        case "export":
          let data = {
            title: this.form.title,
            operName: this.form.operName,
            operatorType: this.form.businessType,
            status: this.form.status,
            "params[beginTime]": this.form.beginTime,
            "params[endTime]": this.form.finishTime,
          };
          operateLogExport(data).then((res) => {
            if (res.code == 0) {
              window.open(res.data.downLoadUrl, "_self");
            } else {
              this.$message({
                type: "error",
                message: res.msg,
              });
            }
          });
          break;
        default:
          break;
      }
    },
    // 处理表头显示隐藏
    handleCheckChange(checkedValues) {
      this.tableHeader.forEach((item) => {
        item.visible = checkedValues.includes(item.prop);
      });
      this.tableKey += 1;
    },
    handleSearchClick() {
      this.searchCardShow = !this.searchCardShow;
    },
    handleInitClick() {
      this.initTable();
    },
    resetTable() {
      this.form = {
        title: "",
        operName: "",
        businessType: "",
        status: "",
        beginTime: "",
        finishTime: "",
      };
      this.createTime = [];
      this.initTable();
    },
    handleSelectTime(val) {
      if (val && val.length) {
        this.form.beginTime = val[0];
        this.form.finishTime = val[1];
      }
    },
    handlerPagination(page) {
      this.currentPage = page.pageNum;
      this.pageSize = page.pageSize;
      this.initTable();
    },
    hasPermission(permission) {
      return hasPermission(permission);
    },
    calculateTableHeight() {
      // 根据容器实际高度计算表格高度
      this.$nextTick(() => {
        const container = this.$refs.multipleTable.$el?.parentElement;
        if (container) {
          // 减去表头和其他元素的高度
          this.tableHeight = container.clientHeight - 120; // 120为估计的其他元素高度
        }
      });
    },
  },
};
</script>
